import serial
import time
import json
from setting import logger
from ble_function import BleFunction


from sensor_command import SensorCommandGenerator

from util import parse_command_to_ascII, parse_ascII_to_command, send_message_by_websocket


from queue import Queue

from auto_ip import get_network_info

from setting import MQTT_LOCAL_HOST, get_mac_address

MAC = get_mac_address()

class BleSentry:

    def __init__(self) -> None:
        
        self.ser = serial.Serial('/dev/ttyS5', 9600)

        self.task_queue = Queue(100)

        self.sensor_command_generator = SensorCommandGenerator()

    
    def start_ble_server(self):

        receive_str = ""

        while True:

            try:

                data = self.ser.read(self.ser.in_waiting).decode()

            except Exception as e:

                logger.error(str(e))

            else:

                if data.startswith("##"):

                    receive_str = ""

                receive_str += data

                if data.endswith("##"):

                    self.task_queue.put(receive_str)

                    logger.info("添加蓝牙任务：")
                    logger.info(receive_str)

    def ble_send(self, data):
        '''蓝牙发送数据'''

        data = "##" + json.dumps(data) + "##"

        logger.info("蓝牙发送信息：")

        logger.info(data)

        self.ser.write(data.encode())

        
    def task_worker(self):

        while True:
            try:

                task = self.task_queue.get()

                task = json.loads(task.replace("##", ""))

            except Exception as e:

                logger.error("处理任务：")
                logger.error(task)
                logger.error(str(e))

            else:

                logger.info("处理任务：")
                logger.info(task)
                self.processing_tasks(task)

    def processing_tasks(self, task): # 任务处理


        if task["task_type"] == "get_sensor_info": # 获取基站信息
            '''
            {
                "task_type": "get_sensor_info",
                "task_id": "2",	# 任务ID号
                "data": ""
            }
            '''
            send_data = BleFunction(MQTT_LOCAL_HOST, MAC).get_sensor_info()

            logger.info(send_data)

            self.ble_send(send_data) # 回调信息

        
        # if task["task_type"] == "get_task_status": # 获取对应的任务状态

        #     '''
        #     {
        #         "task_type": "get_task_status",
        #         "task_id": "2",	# 任务ID号
        #     }
        #     '''

        #     send_data = BleFunction(MQTT_LOCAL_HOST, MAC).get_task_status(task)

        #     logger.info(send_data)

        #     self.ble_send(send_data) # 回调信息

        if task["task_type"] == "get_ip": 

            '''
            {
                "task_type": "get_ip",
                "task_id": "2",	# 任务ID号
            }
            '''

            send_data = get_network_info()

            logger.info(send_data)

            self.ble_send(send_data) # 回调信息



        
        # if task["task_type"] in ["set_acquisition_cycle", "read_acquisition_cycle", "set_reporting_cycle", "read_reporting_cycle", "set_fluctuation_threshold", "read_fluctuation_threshold", "set_alarm_threshold", "read_alarm_threshold"]:
        if task["task_type"] in ["set_acquisition_cycle",  "set_reporting_cycle",  "set_fluctuation_threshold",  "set_alarm_threshold", ]:
            '''
            {
                "task_type": "set_acquisition_cycle",													
                "task_id": "183",																		# 任务ID号
                "data": {
                    "devaddr_list": ["943EBDE7", "92B18DD5"],
                    "value": "00"  # 00:不采集; 01:连续采集; 02:1秒一次; 03:5秒一次; 04:10秒一次； 05：30秒一次； 
                }
            }
            '''
            for devaddr in task["devaddr_list"]:

                command_generator_fun = self.sensor_command_generator.get_function_object(task["task_type"])

                command = parse_command_to_ascII(command_generator_fun(int(task['data']['value'], 16), 66))

                logger.info(f"command:{command}")
                logger.info(f"parse_ascII_to_command:{parse_ascII_to_command(command)}")

                data = {
                    "data": command,
                    "devaddr": devaddr,
                    "port": 12
                }

                send_message_by_websocket(devaddr, json.dumps(data))

                logger.info(data)

            ble_send_data = {"type": "callback"}

            task["task_status"] = "receive"
            task["notes"] = None
            task["result"] = None

            ble_send_data["data"] = task

            self.ble_send(ble_send_data)

        if task["task_type"] in ["read_acquisition_cycle", "read_reporting_cycle", "read_fluctuation_threshold", "read_alarm_threshold"]:
            '''
            { 
                "task_type": "read_reporting_cycle", 
                "task_id": "193", 
                "data": { 
                    "devaddr_list": [ "943EBDE7", "97591E62" ] 
                } 
            }
            '''
            for devaddr in task["devaddr_list"]:

                command_generator_fun = self.sensor_command_generator.get_function_object(task["task_type"])

                command = parse_command_to_ascII(command_generator_fun(88))

                logger.info(f"command:{command}")
                logger.info(f"parse_ascII_to_command:{parse_ascII_to_command(command)}")

                data = {
                    "data": command,
                    "devaddr": devaddr,
                    "port": 12
                }

                send_message_by_websocket(devaddr, json.dumps(data))

                logger.info(send_data)

            ble_send_data = {"type": "callback"}

            task["task_status"] = "receive"
            task["notes"] = None
            task["result"] = None

            ble_send_data["data"] = task

            self.ble_send(ble_send_data)

        if task["task_type"] == "get_senor_info":
            '''

            { 
                "task_type": "get_senor_info", 
                "task_id": "193", 
                "data": { 
                    "devaddr": "943EBDE7", 
                } 
            }
            '''

            devaddr = task["data"]["devaddr"]

            data = BleFunction(MQTT_LOCAL_HOST, MAC).get_sensor_last_data(devaddr)

            result = {
                "raw": data,
                "pase_value": "" # TODO
            }

            ble_send_data = {"type": "callback"}

            task["task_status"] = "receive"
            task["notes"] = None
            task["result"] = result

            ble_send_data["data"] = task

            self.ble_send(ble_send_data)



                




        






        


if __name__ == "__main__":

    from threading import Thread

    bs = BleSentry()

    Thread(target=bs.task_worker).start() # 开启消费线程

    bs.start_ble_server()








# ser = serial.Serial('/dev/ttyS5', 9600)

# file = None

# try:
#     with open('ble_ip_data', 'w') as file:
#         while True:

#             data = ser.read(ser.in_waiting)


#             if data:
#                 print(data.decode())

#                 if data.startswith(b"##"):
#                     ip_address = data[2:].decode()
#                     print("IP地址:",ip_address)

 
#                     with open('ip_data','w') as file: 
#                         file.write(ip_address)
#                         file.flush()
          
#                     with open('ip_data','r') as read_file:  
#                         file_content = read_file.read().strip()
#                         ser.write(file_content.encode())

#                 if data==b'**0101': 
#                     with open('ip_data','r') as read_file:
#                         file_content = read_file.read().strip()
#                         ser.write(file_content.encode())

#                 # if data==b'**0102':
#                 #     with open('/root/.master_station_ip','r') as file:
#                 #         file_content = file.read().strip()
#                 #         ser.write(file_content.encode())
                
#                 else:
#                     print("无效数据")
 

# except KeyboardInterrupt:

#     ser.close()
#     file.close()
